import * as roleService from './service';

export default {
  namespace: 'role',
  state: {
    data: [],
    total: null,
    page: null,
    pageSize: null,
    permisssions:null
  },
  effects: {
    //查询
    *queryRole({ payload: { currentPage } }, { call, put }) {
      const { list, total, page, pageSize } = yield call(roleService.query, { currentPage });

     // console.log('role-list'+JSON.stringify(list))
      yield put({
        type: 'stateHandler',
        payload: {
          list,
          total: parseInt(total, 10),
          page: parseInt(page, 10),
          pageSize: parseInt(pageSize, 10)
        }
      })
    },
    //添加,更新
    *saveRole({ payload: { role } }, { call, put, select }) {
      yield call(roleService.save, { role });
      const page = yield select((state) => state.role.page);
      yield put({
        type: 'queryRole',
        payload: { currentPage: page }
      })
    },
    //删除
    *deleteRole({ payload: { id } }, { call, put, select }) {
      yield call(roleService.del, { id });
      const page = yield select((state) => state.role.page);
      yield put({
        type: 'queryRole',
        payload: { currentPage: page }
      })
    },
    //根据角色id获得对应的权限
    *getPermissionByRoleId({payload:{id}},{call,put,select}){
      const permissions =  yield call(roleService.getPermissionByRoleId,{id});
      const page = yield select((state) => state.role.page);
      //跳转到保存权限
      yield put({
        type: 'savePermissionsByRole',
        payload: {permissions}
      })
      // //权限保存成功后，跳转回当前页
      // yield put({
      //   type: 'queryRole',
      //   payload: { currentPage: page }
      // })
    },
    *saveNewPermissionsByRoleId({ payload: { newPermissions,id}},{call,put,select}){
      yield call(roleService.saveNewPermissionsByRoleId,{newPermissions,id});
      const page = yield select((state) => state.role.page);
      yield put({
        type:'queryRole',
        payload: {currentPage: page}
      })
    }
  },
  reducers: {
    //查询
    stateHandler(state, { payload: { list: data, total, page, pageSize } }) {
      return { ...state, data, total, page, pageSize };
    },
    //保存权限
    savePermissionsByRole(state,{payload:{permissions}}){
      //console.log('model-permissions'+permissions);
      return { ...state,permissions}
    }

  }
}
